import json

from utils.MySqlUtil import MySqlUtil


class Menu:
    def build_menu_tree(self, menu_data, parent_id=0):
        menu_tree = []
        for item in menu_data:
            if item["parent_id"] == parent_id:
                children = self.build_menu_tree(menu_data, item["id"])
                if children:
                    item["child"] = children
                menu_tree.append(item)
        return menu_tree


if __name__ == '__main__':
    db = MySqlUtil()
    menu_data_ = db.query('select * from sys_menu sm ', None)
    data_ = []
    for data in menu_data_:
        temp_ = {
            'id': data['id'],
            'parent_id': data['parent_id'],
            'title': data['menu_title'],
            'icon': data['menu_icon'],
            'href': data['menu_href'],
            'target': data['menu_target'],
        }
        data_.append(temp_)
    menu_tree_json = json.dumps(Menu().build_menu_tree(data_), ensure_ascii=False)
    print(menu_tree_json)
